//
//  AddressManagerViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/10/22.
//  Copyright © 2015年 zhixiao. All rights reserved.
//

import UIKit

class AddressManagerViewController: BaseViewController {
    var tableview:UITableView!
    var tableDataSource:[AddressListItem] = []
    var bottomView:UIView!
    var addBtn:UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "地址管理"
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = commonBackgoundColor
        self.createTableView()
        self.setupBottomView()
        // Do any additional setup after loading the view.
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = false
        if let sessionid = GlobalDataHelper.instance.session{
            self.queryAddressList(sessionid)
        }
        if GlobalDataHelper.instance.proviceObjArray == nil{
            self.queryAddressList()
        }
    }
    func queryAddressList()->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        request.requestStart("/address/getJsonArea", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                if let arry = dic?.pareseDataToProviceArray(){
                    GlobalDataHelper.instance.proviceObjArray = arry
                }
            }
        })
    }
    func queryAddressList(sessionid:String!)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(sessionid, forKey: "sessionid")
        request.requestStart("/address/list", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                if let array = dic?.pareseDataToAddressListArray(){
                    self.tableDataSource = array
                    dispatch_async(dispatch_get_main_queue()){
                        self.tableview.reloadData()
                    }
                }

            }
            else{
                self.showTips("加载失败")
            }
        })
        self.showProcess("加载中...")
    }
    func createTableView(){
        //        leftTableDataSource.addObjectsFromArray(["热门品牌","食品/保健","美妆个护","母婴用品","服饰鞋包","生活数码"])
        tableview = UITableView(frame: CGRectMake(0, 64, view.bounds.size.width, view.bounds.size.height-64-49), style: UITableViewStyle.Grouped)
        tableview.backgroundColor = UIColor.clearColor();
        tableview.separatorStyle = UITableViewCellSeparatorStyle.None
        tableview.showsHorizontalScrollIndicator = false
        tableview.showsVerticalScrollIndicator = false
        tableview.dataSource = self
        tableview.delegate = self
        let nib = UINib(nibName:"AddressCell", bundle:nil)
        tableview.registerNib(nib,forCellReuseIdentifier:"AddressCellID")
        view.addSubview(tableview)
    }
    func setupBottomView(){
        bottomView = UIView(frame: CGRectMake(0, view.bounds.size.height-49, view.bounds.size.width, 49))
        view.addSubview(bottomView)
        //背景
        let line = UIImageView(frame: CGRectMake(0, 0, bottomView.bounds.size.width, onePix))
        line.backgroundColor = commonRedColor
        bottomView.addSubview(line)
        //新建
        addBtn = UIButton(frame: CGRectMake(20,5, bottomView.bounds.size.width - 40, bottomView.bounds.size.height-10))
        addBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        addBtn.setTitle("＋新建地址", forState: UIControlState.Normal)
        addBtn.backgroundColor = commonRedColor
        addBtn.addTarget(self, action: "addBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
        addBtn.layer.cornerRadius = 4.0
        addBtn.titleLabel?.font = UIFont.systemFontOfSize(15)
        bottomView.addSubview(addBtn)
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func addBtnClick(button:UIButton){
        let ctl = UpdateAddressViewController()
        ctl.type = UpdateType.Add
        self.navigationController?.pushViewController(ctl, animated: true)
    }
    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }

}
extension AddressManagerViewController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSectionsInTableView(tableView: UITableView) -> Int{
        return tableDataSource.count
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return 1
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 10
    }
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        return 1
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("AddressCellID", forIndexPath: indexPath) as! AddressCell
        let obj = tableDataSource[indexPath.section]
        cell.indexPath = indexPath
        cell.name.text = "收货人："+obj.username!
        cell.phone.text = obj.telephone
        cell.address.text = obj.content
        if obj.selected == "1"{
            cell.setDefaultBtn.selected = true
            cell.setDefaultBtn.userInteractionEnabled = false
        }
        else{
            cell.setDefaultBtn.selected = false
            cell.setDefaultBtn.userInteractionEnabled = true
        }
        cell.selectValueChangedEnclose = { [weak self] apath in
            let obj = self?.tableDataSource[apath.section]
            let request = NetWorkHelper()
            let parameters = NSMutableDictionary()
            parameters.setObject(GlobalDataHelper.instance.session!, forKey: "sessionid")
            parameters.setObject(obj!.id!, forKey: "address_id")
            request.requestStart("/checkout/setShippingAddress", parameters: parameters,compeleteHandle:{ (data, response, error)  in
                dispatch_async(dispatch_get_main_queue()){
                    self?.hiddenProcessView()
                }
                if error == nil{
                    var dic:NSDictionary?
                    do {
                        dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                    } catch let error as NSError {
                        print(error)
                    }
                    if (dic?["result"])! as! String == "0"{
                        dispatch_async(dispatch_get_main_queue()){
                            self?.showTips("设置成功")
                            if let sessionid = GlobalDataHelper.instance.session{
                                self?.queryAddressList(sessionid)
                            }
                        }
                    }
                    
                }
                else{
                    dispatch_async(dispatch_get_main_queue()){
                        self?.showTips("设置失败")
                    }
                    
                }
            })
            self?.showProcess("处理中...")
            
        }
        cell.editButtonClickHandle = {[weak self] apath in
            let obj = self?.tableDataSource[apath.section]
            let ctl = UpdateAddressViewController()
            ctl.type = UpdateType.Edited
            ctl.address = obj
            self?.navigationController?.pushViewController(ctl, animated: true)
        }
        cell.deleteButtonClickHandle = { [weak self] apath in
            let obj = self?.tableDataSource[apath.section]
            if #available(iOS 8.0, *) {
                let alertController = UIAlertController(title: "是否确认删除该地址", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
                let deleteAction = UIAlertAction(title: "删除", style: UIAlertActionStyle.Destructive){ action in
                    let request = NetWorkHelper()
                    let parameters = NSMutableDictionary()
                    parameters.setObject(GlobalDataHelper.instance.session!, forKey: "sessionid")
                    parameters.setObject(obj!.id!, forKey: "id")
                    request.requestStart("/address/delete", parameters: parameters,compeleteHandle:{ (data, response, error)  in
                        dispatch_async(dispatch_get_main_queue()){
                            self?.hiddenProcessView()
                        }
                        if error == nil{
                            var dic:NSDictionary?
                            do {
                                dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                            } catch let error as NSError {
                                print(error)
                                dispatch_async(dispatch_get_main_queue()){
                                    self?.showTips("数据加载出错")
                                }
                                return
                            }
                            if (dic?["result"])! as! String == "0"{
                                dispatch_async(dispatch_get_main_queue()){
                                    self?.showTips("删除成功")
                                    self?.tableDataSource.removeAtIndex(apath.section)
                                    self?.tableview.reloadData()
                                }
                            }
                            
                        }
                        else{
                            dispatch_async(dispatch_get_main_queue()){
                                self?.showTips("删除失败")
                            }
                            
                        }
                    })
                    self?.showProcess("处理中...")
                    
                }
                let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
                
                alertController.addAction(cancelAction)
                alertController.addAction(deleteAction)
                self?.presentViewController(alertController, animated: true, completion: nil)
            } else {
                // Fallback on earlier versions
            }

            
        }
        return cell;
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        return 110
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        if indexPath.section == 0{
            
        }
        else{

        }
    }
}
